package zzhyc.keystore

import android.content.Context
import android.content.Intent
import android.graphics.Point
import android.os.Bundle
import android.util.Log
import android.view.KeyEvent
import android.widget.FrameLayout
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.qq.e.ads.banner2.UnifiedBannerADListener
import com.qq.e.ads.banner2.UnifiedBannerView
import com.qq.e.ads.interstitial2.UnifiedInterstitialAD
import com.qq.e.ads.interstitial2.UnifiedInterstitialADListener
import com.qq.e.ads.interstitial2.UnifiedInterstitialMediaListener
import com.qq.e.ads.rewardvideo.RewardVideoAD
import com.qq.e.ads.rewardvideo.RewardVideoADListener
import com.qq.e.comm.util.AdError
import zzhyc.keystore.ShouKuaiInfoActivity.Companion
import zzhyc.keystore.ShouKuaiInfoActivity.Companion.SBLOGS
import zzhyc.keystore.databinding.ActivityHlyinfoBinding

private const val TAG = "HLYInfoActivity"

class HLYInfoActivity : AppCompatActivity() {

    private val binding by lazy { ActivityHlyinfoBinding.inflate(layoutInflater) }
    private var unifiedBannerView: UnifiedBannerView? = null
    private var rewardVideoAD: RewardVideoAD? = null
    private var unifiedInterstitialAD: UnifiedInterstitialAD? = null
    private var logStr = StringBuilder()

    companion object {
        const val SBLOGS = "sblogs"
        fun startActivity(context: Context, logs: String) {
            val intent = Intent(context, HLYInfoActivity::class.java)
            intent.putExtra(SBLOGS, logs)
            context.startActivity(intent)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)

        getIntentParams()
        initBanner()
        //激励按钮
        binding.hlyInfoBtnJiLi.setOnClickListener {
            initVideo()
        }

        //插屏
        binding.hlyInfoBtnCha.setOnClickListener {
            initCha()
        }

        //信息流
        binding.hlyInfoBtnDraw.setOnClickListener {
            startActivityForResult(Intent(this, HLYDrawActivity::class.java), 101)
        }
    }

    private fun getIntentParams() {
        intent.extras?.let {
            it.getString(ShouKuaiInfoActivity.SBLOGS)?.let { mLog ->
                setLogsView(mLog)
            }
        }
    }

    //插屏
    private fun initCha() {
        unifiedInterstitialAD =
            UnifiedInterstitialAD(
                this,
                HLYKey.HLY_CHA_APP_ID,
                object : UnifiedInterstitialADListener {
                    override fun onADReceive() {
                        setLogsView("优量汇插屏/onADReceive: \n")
                        setLogsView(
                            "优量汇插屏/onADReceive eCPMLevel = " + unifiedBannerView?.getECPMLevel() +
                                    ", ECPM: " + unifiedBannerView?.getECPM()
                                    + ", testExtraInfo:" + unifiedBannerView?.getExtraInfo()
                                ?.get("mp")
                                    + ", request_id:" + unifiedBannerView?.getExtraInfo()
                                ?.get("request_id") + " \n"
                        )
                    }

                    override fun onVideoCached() {
                        setLogsView("优量汇插屏/onVideoCached: \n")
                    }

                    override fun onNoAD(p0: AdError?) {
                        setLogsView("优量汇插屏/onNoAD: ${p0?.errorCode}，msg-- ${p0?.errorMsg} \n")
                    }

                    override fun onADOpened() {
                        setLogsView("优量汇插屏/onADOpened:  \n")
                    }

                    override fun onADExposure() {
                        setLogsView("优量汇插屏/onADExposure:  \n")
                    }

                    override fun onADClicked() {
                        setLogsView("优量汇插屏/onADClicked:  \n")
                    }

                    override fun onADLeftApplication() {
                        setLogsView("优量汇插屏/onADLeftApplication:  \n")
                    }

                    override fun onADClosed() {
                        setLogsView("优量汇插屏/onADClosed:  \n")
                    }

                    override fun onRenderSuccess() {
                        setLogsView("优量汇插屏/onRenderSuccess:  \n")
                        unifiedInterstitialAD?.let {
                            if (it.isValid) {
                                it.showFullScreenAD(this@HLYInfoActivity)
                            }
                        }
                    }

                    override fun onRenderFail() {
                        setLogsView("优量汇插屏/onRenderFail:  \n")
                    }
                })
        unifiedInterstitialAD?.setMediaListener(object : UnifiedInterstitialMediaListener {
            override fun onVideoInit() {
                setLogsView("优量汇插屏/onVideoInit:  \n")
            }

            override fun onVideoLoading() {
                setLogsView("优量汇插屏/onVideoLoading:  \n")
            }

            override fun onVideoReady(p0: Long) {
                setLogsView("优量汇插屏/onVideoReady:  \n")
            }

            override fun onVideoStart() {
                setLogsView("优量汇插屏/onVideoStart:  \n")
            }

            override fun onVideoPause() {
                setLogsView("优量汇插屏/onVideoPause:  \n")
            }

            override fun onVideoComplete() {
                setLogsView("优量汇插屏/onVideoComplete:  \n")
            }

            override fun onVideoError(p0: AdError?) {
                setLogsView("优量汇插屏/onVideoError: ${p0?.errorCode}，msg-- ${p0?.errorCode} \n")
            }

            override fun onVideoPageOpen() {
                setLogsView("优量汇插屏/onVideoPageOpen:  \n")
            }

            override fun onVideoPageClose() {
                setLogsView("优量汇插屏/onVideoPageClose:  \n")
            }
        })
        unifiedInterstitialAD?.loadFullScreenAD()
    }

    private fun initBanner() {
        binding.hlyInfoBanner.removeAllViews()
        unifiedBannerView =
            UnifiedBannerView(this, HLYKey.HLY_BANNER_APP_ID, object : UnifiedBannerADListener {
                override fun onNoAD(p0: AdError?) {
                    setLogsView("banner/onNoAD: ${p0?.errorCode}，msg-- ${p0?.errorMsg} \n")
                }

                override fun onADReceive() {
                    setLogsView(
                        "banner加载成功/onADReceive eCPMLevel = " + unifiedBannerView?.getECPMLevel() +
                                ", ECPM: " + unifiedBannerView?.getECPM()
                                + ", testExtraInfo:" + unifiedBannerView?.getExtraInfo()?.get("mp")
                                + ", request_id:" + unifiedBannerView?.getExtraInfo()
                            ?.get("request_id") + " \n"
                    )
                }

                override fun onADExposure() {
                }

                override fun onADClosed() {
                }

                override fun onADClicked() {
                }

                override fun onADLeftApplication() {
                }
            })
        binding.hlyInfoBanner.addView(unifiedBannerView, getUnifiedBannerLayoutParams())
        unifiedBannerView?.loadAD()
    }

    //激励
    private fun initVideo() {
        rewardVideoAD = RewardVideoAD(this, HLYKey.HLY_JILI_APP_ID, object : RewardVideoADListener {
            override fun onADLoad() {
                setLogsView("优量汇激励视频/onADLoad:  \n")
                setLogsView(
                    "优量汇激励视频/eCPMLevel = " + rewardVideoAD?.getECPMLevel()
                            + ", ECPM: " + rewardVideoAD?.getECPM()
                            + ", testExtraInfo:" + rewardVideoAD?.getExtraInfo()?.get("mp")
                            + ", request_id:" + rewardVideoAD?.getExtraInfo()
                        ?.get("request_id") + " \n"
                )
                rewardVideoAD?.isValid?.let {
                    rewardVideoAD?.showAD(this@HLYInfoActivity)
                }
            }

            override fun onVideoCached() {
                setLogsView("优量汇激励视频/onVideoCached:  \n")
            }

            override fun onADShow() {
                setLogsView("优量汇激励视频/onADShow:  \n")
            }

            override fun onADExpose() {
                setLogsView("优量汇激励视频/onADExpose:  \n")
            }

            override fun onReward(p0: MutableMap<String, Any>?) {
                setLogsView("优量汇激励视频/onReward:  \n")
            }

            override fun onADClick() {
                setLogsView("优量汇激励视频/onADClick:  \n")
            }

            override fun onVideoComplete() {
                setLogsView("优量汇激励视频/onVideoComplete:  \n")
            }

            override fun onADClose() {
                setLogsView("优量汇激励视频/onADClose:  \n")

            }

            override fun onError(p0: AdError?) {
                setLogsView("优量汇激励视频/onError: ${p0?.errorCode}，msg-- ${p0?.errorMsg} \n")
            }
        }, false)
        rewardVideoAD?.loadAD()
    }

    private fun getUnifiedBannerLayoutParams(): FrameLayout.LayoutParams {
        val screenSize = Point()
        windowManager.defaultDisplay.getSize(screenSize)
        return FrameLayout.LayoutParams(screenSize.x, Math.round(screenSize.x / 6.4F))
    }

    /**
     *  将所有的日志显示到textView上
     */
    private fun setLogsView(logs: String) {
        Log.i(TAG, logs)
        logStr.append(logs)
        if (logStr.isNotEmpty()) {
            binding.hlyInfoTvLog.text = logStr.toString()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 101 && resultCode == RESULT_OK) {
            data?.getStringExtra("drawLogs")?.let { appendLog ->
                logStr.append(appendLog)
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        unifiedBannerView?.destroy()
        unifiedInterstitialAD?.destroy()
    }

    private var mExitTime: Long = 0
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (System.currentTimeMillis() - mExitTime > 2000) {
                Toast.makeText(this, getString(R.string.exit_program), Toast.LENGTH_SHORT).show()
                mExitTime = System.currentTimeMillis()
            } else {
                if (!this.isFinishing) {
                    finishAndRemoveTask()
                }
            }
            return true
        }
        return super.onKeyDown(keyCode, event)
    }
}